home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: Please help: need to read lines in text file
- Date: 1 Apr 1996 07:56:43 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4joubrINNrdl@keats.ugrad.cs.ubc.ca>
- References: <315fe5d1.1121568@news.mixcom.com>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <315fe5d1.1121568@news.mixcom.com>,
- Mike McWhinney <elja.inc@mixcom.com> wrote:
- >Hello all,
- >
- >I am not an especially fluent C programmer, but need a short function
- >to read the Nth line from a given ASCII/text file. The target
- >platform is MS-DOS, and the compiler I have is Turbo C++, but
- >shouldn't matter if it is portable C code.
-
- #include <stdio.h>
- #include <stdlib.h>
-
- #define INITIAL_BUFSIZE 80
- #define BUFSIZE_INCREM 40
-
- char *readline(char *filename, int n)
-
- {
- FILE *stream = fopen(filename,"r");
- int currline = 1;
- int buffersize = INITIAL_BUFSIZE;
- int charcount = 0;
- char *buffer, *newbuffer;
- int nextchar;
-
- if (!stream)
- goto errquit;
-
- buffer = malloc(buffersize);
-
- while (currline < n) {
- if((nextchar = getc(stream)) == '\n') {
- currline++;
- continue;
- } else if (nextchar == EOF) {
- fclose(stream);
- goto ferrquit;
- }
- }
-
- while(1) {
- nextchar = getc(stream);
-
- if (charcount >= buffersize) {
- buffersize += BUFSIZE_INCREM;
- newbuffer = realloc(buffer, buffersize);
- if (!newbuffer)
- goto ferrquit;
- buffer = newbuffer;
- }
-
- if (nextchar == EOF || nextchar == '\n') {
- buffer[charcount++] = '\0';
- break;
- } else
- buffer[charcount++] = nextchar;
- }
- return realloc(buffer, charcount);
-
- ferrquit:
- free(buffer);
- errquit:
- return NULL;
- }
-
- int main(int argc, char **argv)
-
- {
- char *str;
-
- if (argc < 3)
- exit(EXIT_FAILURE);
-
- str = readline(argv[1], atoi(argv[2]));
-
- if (!str) {
- puts("failure to read line");
- exit(EXIT_FAILURE);
- } else
- puts(str);
-
- return EXIT_SUCCESS;
- }
-
- --
-
-